﻿using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using Common;

namespace YyMoney
{
    /// <summary>
    ///     MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        //当前需要编辑或删除的行所对应于数据库中的id号
        private object _id;

        //当前所在页
        private int _pageIndex;

        private int _pageSize = 10;

        //总页数
        private int _pageCount;

        private int _rowCount;

        //查询yydeal语句，第一个参数是pageIndex当前所在页，第二个参数是pageCount每页行数
        private const string QueryDeal = "select * from yydeal limit {0},{1};";

        //查询yydeal行数
        private const string QueryRowCount = "select count(*) from yydeal;";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _rowCount = int.Parse(MySqlCommon.Instance.ExecuteScalar(QueryRowCount).ToString());
                _pageIndex = _rowCount/_pageSize;
            }
            catch (System.Data.Common.DbException ex)
            {
                MessageBox.Show(ex.Message);
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            UpdateTable();

            //初始化日期框为当天
            DpDate.Text = DateTime.Now.ToShortDateString();
        }

        /// <summary>
        /// 更新表DgMoney的数据
        /// </summary>
        private void UpdateTable()
        {
            DgMoney.ItemsSource = MySqlCommon.Instance.GetTable(string.Format(QueryDeal, _pageIndex * _pageSize, 10)).DefaultView;
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string checkStr = CheckInput();

            if (checkStr != null)
            {
                MessageBox.Show(checkStr);
                return;
            }

            int val;

            try
            {
                string sql = string.Format("insert into yydeal(Date,Name,Money,Sum)values('{0}','{1}',{2},{3})",
                                           DpDate.Text, TxtName.Text, TxtMoney.Text, TxtSum.Text);

                val = MySqlCommon.Instance.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加失败:" + ex.Message);
                return;
            }

            if (val == 1)
            {
                if (((DataView)DgMoney.ItemsSource).Table.Rows.Count == _pageSize)
                {
                    _pageIndex++;
                }

                UpdateTable();
                MessageBox.Show("添加成功");
            }
            else
            {
                MessageBox.Show("添加失败");
            }
        }

        private string CheckInput()
        {
            if (DpDate.Text == "")
            {
                return "日期不能为空";
            }

            if (TxtName.Text == "")
            {
                return "交易名字不能为空";
            }

            if (TxtMoney.Text == "")
            {
                return "金额不能为空";
            }

            if (TxtOldSum.Text == "")
            {
                return "原余额不能为空";
            }

            double oldSum;

            if (!double.TryParse(TxtOldSum.Text, out oldSum))
            {
                return "原余额必须是浮点数";
            }

            double money;

            if (!double.TryParse(TxtMoney.Text, out money))
            {
                return "金额必须是浮点数";
            }

            TxtSum.Text = (oldSum + money).ToString(CultureInfo.InvariantCulture);
            return null;
        }

        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            string checkStr = CheckInput();

            if (checkStr != null)
            {
                MessageBox.Show(checkStr);
                return;
            }

            int val;

            try
            {
                string sql = string.Format("update yydeal set Date='{0}',Name='{1}',Money={2},Sum={3} where Id={4}",
                                           DpDate.Text, TxtName.Text, TxtMoney.Text, TxtSum.Text, _id);

                val = MySqlCommon.Instance.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改失败:" + ex.Message);
                return;
            }

            if (val == 1)
            {
                UpdateTable();
                MessageBox.Show("修改成功");
            }
            else
            {
                MessageBox.Show("修改失败");
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定删除？", "提示", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                return;
            }

            int val;

            try
            {
                val = MySqlCommon.Instance.ExecuteNonQuery("delete from yydeal where Id=" + _id);
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败:" + ex.Message);
                return;
            }

            if (val == 1)
            {
                if (((DataView)DgMoney.ItemsSource).Table.Rows.Count == 1)
                {
                    _pageIndex = _pageIndex == 0 ? 1 : _pageIndex - 1;
                }

                UpdateTable();
                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }

        private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                object[] items = ((DataRowView) DgMoney.CurrentCell.Item).Row.ItemArray;
                _id = items[0];
                DpDate.Text = items[1].ToString();
                TxtName.Text = items[2].ToString();
                string money = items[3].ToString();
                TxtMoney.Text = money;
                string sum = items[4].ToString();
                TxtSum.Text = sum;
                TxtOldSum.Text = (double.Parse(sum) - double.Parse(money)).ToString(CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void BtnUpdate_Click(object sender, RoutedEventArgs e)
        {
            UpdateTable();
        }
    }
}